package com.accountant.travelaccountant;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class FrontScreen extends Activity {
	Button newAccount, exixtingAccount;
	private static int noOfTimesPressed = 0;
	DatabaseOperations_NonActivity databaseOperations;
	ArrayList<String> arrListOfUniqueNames, checkAnyNames;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		/* Code to put in all the unique names into the database */
		databaseOperations = new DatabaseOperations_NonActivity(
				getApplicationContext());
		databaseOperations.openWriteableDatabase();
		checkAnyNames = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getUniquenamestable(),
				new String[] { DatabaseOperations_NonActivity
						.getUniquenamestablenames() }, null, null, null, null,
				null);

		if (checkAnyNames.size() == 0) {
			arrListOfUniqueNames = databaseOperations.retrieveAll(
					DatabaseOperations_NonActivity.getMembertable(),
					new String[] { DatabaseOperations_NonActivity
							.getMembertablemember() }, null, null,
					DatabaseOperations_NonActivity.getMembertablemember(),
					null, null);
			for (String str : arrListOfUniqueNames) {
				databaseOperations.insertIntoTable(
						DatabaseOperations_NonActivity.getUniquenamestable(),
						Utils_NotActivity.uniqueNamesTableColumns(),
						new ArrayList<String>(Arrays.asList(str)));
			}
		}

		databaseOperations.closeDatabase();

		/* Initialising so that it starts fresh every time */
		setNoOfTimesPressed(0);

		newAccount = (Button) findViewById(R.id.newAccount);
		exixtingAccount = (Button) findViewById(R.id.existingAccount);

		/* Here we will write the code for action on clicking the button */
		newAccount.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(FrontScreen.this, AddMember.class);
				startActivity(intent);
			}
		});

		exixtingAccount.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(FrontScreen.this,
						ChooseAccount2.class);
				startActivity(intent);
			}
		});

	}

	@Override
	public void onBackPressed() {
		setNoOfTimesPressed(getNoOfTimesPressed() + 1);

		if (getNoOfTimesPressed() > 1) {
			finish();
			setNoOfTimesPressed(0);
		} else {
			Toast.makeText(getApplicationContext(), "Press again to exit",
					Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		setNoOfTimesPressed(0);
	}

	public static int getNoOfTimesPressed() {
		return noOfTimesPressed;
	}

	public static void setNoOfTimesPressed(int noOfTimesPressed) {
		FrontScreen.noOfTimesPressed = noOfTimesPressed;
	}

}
